using Services;
using UnityEngine;

public class SaveManager : Service
{
    [Other]
    private EventSystem eventSystem;

    [SerializeField]
    private RuntimeSaveData data;
    public RuntimeSaveData Data => data;

    [SerializeField]
    private InitData init;

    private string savePath;
    private string subSavePath;

    protected override void Awake()
    {
        base.Awake();
        savePath = FileTool.CombinePath(Application.persistentDataPath, "save.json");
        subSavePath = FileTool.CombinePath(Application.persistentDataPath, "subSave.json");
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.O))
            Save();
    }

    public void Save()
    {
        eventSystem.Invoke(EEvent.Save, data);
        JsonTool.SaveAsJson(Data, savePath);
        if (SceneController.AtHome)
            JsonTool.SaveAsJson(Data, subSavePath);
    }

    public void Load()
    {
        data = JsonTool.LoadFromJson<RuntimeSaveData>(savePath);
        if (data == null)
            data = new RuntimeSaveData(init);
        eventSystem.Invoke(EEvent.Load, data);
    }

    public void LoadSub()
    {
        data = JsonTool.LoadFromJson<RuntimeSaveData>(subSavePath);
        if (data == null)
            data = JsonTool.LoadFromJson<RuntimeSaveData>(subSavePath);
        eventSystem.Invoke(EEvent.Load, data);
    }
}